<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <title>1_引出生命周期</title>
</head>

<body>
    <div id="test"></div>
    <script type="text/javascript" src="../js/react.development.js"></script>
    <script type="text/javascript" src="../js/react-dom.development.js"></script>
    <script type="text/javascript" src="../js/babel.min.js"></script>
    <script type="text/babel">
        //1 创建类式组件
        class Life extends React.Component {
            state = {
                opacity: 1,
                add: false
            }
            componentDidMount() {
                //晚于 componentDidMount 调用
                //只调用一次
                console.log("componentDidMount...")
                this.timer = setInterval(() => {
                    let { opacity, add } = this.state
                    if (add) {
                        if (this.state.opacity >= 1) {
                            add = false
                            opacity = 1
                        } else {
                            opacity += 0.05
                        }
                    } else {
                        if (this.state.opacity <= 0) {
                            add = true
                            opacity = 0
                        }else{
                            opacity -= 0.05
                        }
                    }
                    this.setState({ opacity,add })
                }, 100)
            }
            componentWillUnmount(){
                clearInterval(this.timer)
            }
            render() {
                //先于 componentDidMount 调用
                //然后 多次调用
                console.log("render...")
                return (
                    <div>
                        <div style={{ opacity: this.state.opacity }}>哈哈哈</div>
                        <input type='button' onClick={this.hide} value='消失' />
                    </div>
                )
            }
            hide = () => {
                ReactDOM.unmountComponentAtNode(document.getElementById('test'))
            }
        }
        //2 渲染组件到页面 
        ReactDOM.render(<Life />, document.getElementById('test'))
    </script>
</body>
</html>